package com.pd.modules.client.database;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Observable;

import com.pd.modules.client.Client;
import com.pd.modules.common.DateInterval;
import com.pd.modules.common.Message;
import com.pd.modules.common.MessageType;
import com.pd.modules.common.Room;
import com.pd.modules.common.Settings;

public class DBRoomsHandler extends Observable
{
	DateInterval mDateFilter = null;
	Room[] mRooms = null;

	public synchronized Room[] getAllRooms()
	{
		return mRooms;
	}

	public synchronized Room getRoom(String _roomID)
	{
		for (int i = 0; i < mRooms.length; i++)
			if (mRooms[i].getID().equals(_roomID))
				return mRooms[i];

		return null;
	}

	public DateInterval getDateFilter()
	{
		return mDateFilter;
	}

	public boolean dateFilterContains(Date _date)
	{
		return mDateFilter == null ? false : mDateFilter.contains(_date);
	}

	private void dataChanged()
	{
		setChanged();
		notifyObservers();
	}

	public synchronized void setData(Room[] _newData)
	{
		mRooms = _newData;
		dataChanged();
	}

	public synchronized void setDateFilter(DateInterval _newDateFilter)
	{
		mDateFilter = _newDateFilter;
		refresh();
	}

	public void refresh()
	{
		Message tmpMessage = null;

		if (null == mDateFilter)
		{
			tmpMessage = new Message(MessageType.ListAllRooms);
		} else
		{
			tmpMessage = new Message(MessageType.ListAvailableRooms);

			DateFormat formatter = new SimpleDateFormat(Settings.DATE_HOUR_FORMAT);
			tmpMessage.addData(formatter.format(mDateFilter.getStartAsDate()));
			tmpMessage.addData(formatter.format(mDateFilter.getEndAsDate()));
		}

		Client.getInstance().sendMessageToServer(tmpMessage, true);
	}

	public void parseDataFromMessage(Message _message)
	{
		if (_message.getDataSize() == 0)
			setData(null);

		Room[] tmpArray = new Room[_message.getDataSize()];
		for (int i = 0; i < tmpArray.length; i++)
		{
			String asFileEntry = _message.getData(i, String.class);
			tmpArray[i] = new Room(asFileEntry);
		}

		setData(tmpArray);
	}

	public synchronized void clearAllFilters()
	{
		mDateFilter = null;
		refresh();
	}

	public synchronized void clear()
	{
		clearAllFilters();
		mRooms = null;
		dataChanged();
	}
}
